/*
 * Copyright 2020-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.server.authorization.token;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Date;
import java.util.UUID;

import org.springframework.lang.Nullable;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * An {@link OAuth2TokenGenerator} that generates a {@link Jwt}
 * used for an {@link OAuth2AccessToken} or {@link OidcIdToken}.
 *
 * @author Joe Grandja
 * @since 0.2.3
 * @see OAuth2TokenGenerator
 * @see Jwt
 * @see JwtEncoder
 * @see OAuth2TokenCustomizer
 * @see JwtEncodingContext
 * @see OAuth2AccessToken
 * @see OidcIdToken
 */
public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> {
	//默认为NimbusJwtEncoder,里面的jwkSource为我们在配置类AuthorizationServiceConfig中定义的
	private final JwtEncoder jwtEncoder;
	private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer;

	/**
	 * Constructs a {@code JwtGenerator} using the provided parameters.
	 *
	 * @param jwtEncoder the jwt encoder
	 */
	public JwtGenerator(JwtEncoder jwtEncoder) {
		Assert.notNull(jwtEncoder, "jwtEncoder cannot be null");
		this.jwtEncoder = jwtEncoder;
	}
    //JWT包含三部分数据:
	//(1)Header：头部，记录令牌类型、签名算法等 例如：{“alg":"HS256","type","JWT}
	//(2)Payload：载荷，就是有效数据，一般包含下面信息:用户身份信息（注意，这里因为采用base64编码，可解码是可逆的，因此不要存放敏感信息）
	//注册声明：如token的签发时间，过期时间，签发人等 这部分内容 好比身份证的信息 这部分也会采用base64编码，得到第二部分数据
	//(3)Signature：签名，是整个数据的认证信息。一般根据前两步的数据，再加上密钥（secret）（不要泄漏，最好周期性更换），通过加密算法（不可逆的）生成一个签名。
	//防止Token被篡改、确保安全性 例如 计算出来的签名，一个字符串。
	@Nullable
	@Override
	public Jwt generate(OAuth2TokenContext context) {
		//如果token类型为null 或者 token类型不是access_token 或者token类型不是id_token 那么直接返回null
		if (context.getTokenType() == null ||
				(!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType()) &&
						!OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue()))) {
			return null;
		}
		// 如果token类型是access_token，但是数据库或者内存中注册的客户端信息 生成token使用的方式不是self-contained
		// 那么直接返回null，使用OAuth2AccessTokenGenerator来生成access_token
		if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType()) &&
				!OAuth2TokenFormat.SELF_CONTAINED.equals(context.getRegisteredClient().getTokenSettings().getAccessTokenFormat())) {
			return null;
		}

		String issuer = null;
		//context.getAuthorizationServerContext()得到的为安全环境上下文，里面封装了我们配置的各个url信息，再AuthorizationServerContextFilter中初始化的
		//此处issuer即我们授权服务器的地址 http://127.0.0.1:8083/authorizationProject
		if (context.getAuthorizationServerContext() != null) {
			issuer = context.getAuthorizationServerContext().getIssuer();
		}
		//获取认证的客户端信息
		RegisteredClient registeredClient = context.getRegisteredClient();
		//token生成时间
		Instant issuedAt = Instant.now();
		Instant expiresAt;
		//jwt默认加密算法RS256(非对称加密)
		JwsAlgorithm jwsAlgorithm = SignatureAlgorithm.RS256;
		if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
			// TODO Allow configuration for ID Token time-to-live
			//过期时间(30分钟)
			expiresAt = issuedAt.plus(30, ChronoUnit.MINUTES);
			//注册的客户端中是否设置了id-token-signature-algorithm对应的值(jwt加密算法)
			if (registeredClient.getTokenSettings().getIdTokenSignatureAlgorithm() != null) {
				jwsAlgorithm = registeredClient.getTokenSettings().getIdTokenSignatureAlgorithm();
			}
		} else {
			//access_token失效时间 默认7200秒 2小时
			expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getAccessTokenTimeToLive());
		}

		// @formatter:off
		// 创建一个JwtClaimsSet的构造器，里面含有一个claims(声明：包含授权服务器的地址，认证用户名称，认证客户端id等信息)属性Map集合
		// 如果是access_token该claims集合最终会被存储到oauth2_authorization.access_token_metadata字段中,返回到客户端的access_token是不携带这部分信息的
		// 如果是Id_token该claims集合最终会被存储到oauth2_authorization.oidc_id_token_metadata字段中，同时会封装到OidcIdToken对象返回到客户端
		JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder();
		if (StringUtils.hasText(issuer)) {
			//设置授权服务器地址
			claimsBuilder.issuer(issuer);
		}
		claimsBuilder
				//设置用户名
				.subject(context.getPrincipal().getName())
				//设置认证客户端id
				.audience(Collections.singletonList(registeredClient.getClientId()))
				//设置令牌生成发出时间
				.issuedAt(issuedAt)
				//设置失效时间
				.expiresAt(expiresAt)
				//设置uuid
				.id(UUID.randomUUID().toString());
		if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
			//设置生效时间
			claimsBuilder.notBefore(issuedAt);
			if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) {
				//context.getAuthorizedScopes()最原始的客户端发起的授权请求中的scope参数
				claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes());
			}
		} else if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
			//将认证过的客户端id存入claim集合，key为azp
			claimsBuilder.claim(IdTokenClaimNames.AZP, registeredClient.getClientId());
			//是否为授权码模式
			if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType())) {
				//获取最原始的客户端发起的授权请求信息(包含URL和参数信息)
				OAuth2AuthorizationRequest authorizationRequest = context.getAuthorization().getAttribute(
						OAuth2AuthorizationRequest.class.getName());
				//获取客户端传递过来的NONCE,只有scope包含openId的时候才会传递该参数，跟state(csrf攻击)一样都是随机生成的，用来防止重放攻击
				String nonce = (String) authorizationRequest.getAdditionalParameters().get(OidcParameterNames.NONCE);
				//如果nonce参数不为null，则存入claim集合 key为nonce
				if (StringUtils.hasText(nonce)) {
					claimsBuilder.claim(IdTokenClaimNames.NONCE, nonce);
				}
				//获取认证用户最近的session信息
				SessionInformation sessionInformation = context.get(SessionInformation.class);
				if (sessionInformation != null) {
					//将使用的有效的sessionId存入claim集合，key为sid
					claimsBuilder.claim("sid", sessionInformation.getSessionId());
					//将session最近使用时间存入claim集合，key为auth_time
					claimsBuilder.claim(IdTokenClaimNames.AUTH_TIME, sessionInformation.getLastRequest());
				}
			//是否为令牌刷新模式
			} else if (AuthorizationGrantType.REFRESH_TOKEN.equals(context.getAuthorizationGrantType())) {
				//如果为令牌刷新模式，说明之前应该已经产生过idToken,获取其信息
				OidcIdToken currentIdToken = context.getAuthorization().getToken(OidcIdToken.class).getToken();
				//将已存在的idToken中的sessionId以及session最近使用的时间设置到新的idToken中
				if (currentIdToken.hasClaim("sid")) {
					claimsBuilder.claim("sid", currentIdToken.getClaim("sid"));
				}
				if (currentIdToken.hasClaim(IdTokenClaimNames.AUTH_TIME)) {
					claimsBuilder.claim(IdTokenClaimNames.AUTH_TIME, currentIdToken.<Date>getClaim(IdTokenClaimNames.AUTH_TIME));
				}
			}
		}
		// @formatter:on
		//创建头部对象建造器并且将加密算法初始化到建造器中
		JwsHeader.Builder jwsHeaderBuilder = JwsHeader.with(jwsAlgorithm);
		//OAuth2TokenEndpointConfigurer配置类初始化的时候会获取容器中OAuth2TokenCustomizer的实现类泛型为JwtEncodingContext 注入到该属性
		if (this.jwtCustomizer != null) {
			// @formatter:off
			JwtEncodingContext.Builder jwtContextBuilder = JwtEncodingContext.with(jwsHeaderBuilder, claimsBuilder)
					.registeredClient(context.getRegisteredClient())
					.principal(context.getPrincipal())
					.authorizationServerContext(context.getAuthorizationServerContext())
					.authorizedScopes(context.getAuthorizedScopes())
					.tokenType(context.getTokenType())
					.authorizationGrantType(context.getAuthorizationGrantType());
			if (context.getAuthorization() != null) {
				jwtContextBuilder.authorization(context.getAuthorization());
			}
			if (context.getAuthorizationGrant() != null) {
				jwtContextBuilder.authorizationGrant(context.getAuthorizationGrant());
			}
			if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
				SessionInformation sessionInformation = context.get(SessionInformation.class);
				if (sessionInformation != null) {
					jwtContextBuilder.put(SessionInformation.class, sessionInformation);
				}
			}
			// @formatter:on

			JwtEncodingContext jwtContext = jwtContextBuilder.build();
			//可以对jwsHeaderBuilder, claimsBuilder进行自定义调整
			this.jwtCustomizer.customize(jwtContext);
		}
		//创建JwsHeader对象
		JwsHeader jwsHeader = jwsHeaderBuilder.build();
		//创建claims(声明)对象
		JwtClaimsSet claims = claimsBuilder.build();
		//通过NimbusJwtEncoder按照jwt的格式生成最终的jwt对象
		Jwt jwt = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims));

		return jwt;
	}

	/**
	 * Sets the {@link OAuth2TokenCustomizer} that customizes the
	 * {@link JwtEncodingContext#getJwsHeader() JWS headers} and/or
	 * {@link JwtEncodingContext#getClaims() claims} for the generated {@link Jwt}.
	 *
	 * @param jwtCustomizer the {@link OAuth2TokenCustomizer} that customizes the headers and/or claims for the generated {@code Jwt}
	 */
	public void setJwtCustomizer(OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer) {
		Assert.notNull(jwtCustomizer, "jwtCustomizer cannot be null");
		this.jwtCustomizer = jwtCustomizer;
	}

}
